//
//  MyWebViewController.m
//  minshengbank
//
//  Created by mac on 16/11/6.
//  Copyright © 2016年 王. All rights reserved.
//

#import "MyWebViewController.h"
#import <WebKit/WebKit.h>
@interface MyWebViewController ()<UIWebViewDelegate,UIPrintInteractionControllerDelegate>
@property (strong, nonatomic)WKWebView *webView;
@property(nonatomic,strong)UIPrintInteractionController *printCtr;

@end

@implementation MyWebViewController
-(void)dealloc{
    self.printCtr=nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.backgroundColor=[UIColor clearColor];
    self.edgesForExtendedLayout=UIRectEdgeNone;
    NSString *image=[ICrEAMTool isVW]?@"print_vw":@"print_sk";
    UIButton *btn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btn addTarget:self action:@selector(print) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc] initWithCustomView:btn];
    [rightItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                       [UIFont fontWithName:@"HelveticaNeue" size:14.0], NSFontAttributeName,
                                       [UIColor whiteColor], NSForegroundColorAttributeName,
                                       nil]
                             forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem=rightItem;
    self.navigationItem.rightBarButtonItem.enabled=NO;
    [self.view addSubview:self.webView];
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:self.urlStr]];
    request.HTTPShouldHandleCookies=YES;
//设置cookie
    NSArray *arr=[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    if (!IsArrEmpty(arr)) {
        NSHTTPCookie *cookie=arr[0];
        NSString *value=[NSString stringWithFormat:@"%@=%@",[cookie valueForKey:NSHTTPCookieName],[cookie valueForKey:NSHTTPCookieValue]];
            [request setValue:value forHTTPHeaderField:@"Cookie"];
       
    }
    [self.webView loadRequest:request];
      

    // Do any additional setup after loading the view from its nib.
}
-(void)print{
    if (!self.printCtr) {
         self.printCtr = [UIPrintInteractionController sharedPrintController];
    }

    if(!self.printCtr){
        NSLog(@"Couldn't get shared UIPrintInteractionController!");
        return;
    }
    UIPrintInteractionCompletionHandler completionHandler =
    ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if(!completed && error){
            NSLog(@"FAILED! due to error in domain %@ with error code %lu", error.domain, error.code);
        }
    };
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
   
    printInfo.outputType = UIPrintInfoOutputGeneral;
     printInfo.jobName=@"my print job";
//    printInfo.duplex = UIPrintInfoDuplexLongEdge;
//    printInfo.orientation = UIPrintInfoOrientationPortrait;
    self.printCtr.printInfo = printInfo;

    self.printCtr.showsPageRange = YES;
    UIPrintPageRenderer *myRenderer = [[UIPrintPageRenderer alloc] init];
    UIViewPrintFormatter *viewFormatter = [self.webView viewPrintFormatter];
    
    [myRenderer addPrintFormatter:viewFormatter startingAtPageAtIndex:0];
    self.printCtr.printPageRenderer = myRenderer;
    if (self.printType==BalancePrintType) {
        self.printCtr.delegate=self;
    }
    //   iPad
//    [controller presentFromBarButtonItem:barButton animated:YES completionHandler:completionHandler];  // iPad
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= 90000
    [self.printCtr presentFromRect:CGRectMake(100, 200, 200, 200) inView:self.view animated:YES completionHandler:completionHandler];
    
#endif
    [self.printCtr presentFromRect:CGRectMake(0, 0, 200, 200) inView:self.view animated:YES completionHandler:completionHandler];
    
}
- (void)printInteractionControllerDidPresentPrinterOptions:(UIPrintInteractionController *)printInteractionController{
        NSLog(@"-----");
    
}
- (UIPrintPaper *)printInteractionController:(UIPrintInteractionController *)printInteractionController choosePaper:(NSArray<UIPrintPaper *> *)paperList{
   
    CGSize size=CGSizeMake(595.27559055118115,419.5275590551181);
    if (self.printType==BalancePrintType) {
        size=CGSizeMake(21.59/2.54*72,27.94/2.54*72);
    }
    NSLog(@"想要打印的尺寸%@", NSStringFromCGSize(size));
    NSLog(@"打印机支持的尺寸");
    for (UIPrintPaper *p in paperList) {
        NSLog(@"%@--",NSStringFromCGSize(p.paperSize));
        //(width = 252, height = 360)
        //(width = 288, height = 432) 委托书尺寸
        //(width = 297.63779527559058, height = 419.5275590551181)
        //(width = 595.27559055118115, height = 841.88976377952758)
        //(width = 612, height = 792)
    }
    
    UIPrintPaper *paper=[UIPrintPaper bestPaperForPageSize:size withPapersFromArray:paperList];
    NSLog(@"最终尺寸：%@", NSStringFromCGSize(paper.paperSize));
    return paper;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(WKWebView *)webView{
    if (!_webView) {
        
//        //创建网页配置对象
//        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
//        // 创建设置对象
//        WKPreferences *preference = [[WKPreferences alloc]init];
//        // 设置字体大小(最小的字体大小)
//        preference.minimumFontSize = 40;
//        // 设置偏好设置对象
//        config.preferences = preference;
        
        
        _webView=[[WKWebView alloc]initWithFrame:self.view.bounds];
        _webView.backgroundColor=[UIColor clearColor];
        [_webView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
        [_webView setNavigationDelegate:self];
        [_webView setUIDelegate:self];
        [_webView setMultipleTouchEnabled:YES];
        [_webView setAutoresizesSubviews:YES];
        [_webView.scrollView setAlwaysBounceVertical:YES];
        [_webView setAllowsBackForwardNavigationGestures:true];
  
    }
    return _webView;
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
     self.navigationItem.rightBarButtonItem.enabled=YES;
 
}
@end
